package sy6_Behavioral_Pattern.mediator.temp2;

/*
 * 角色共有抽象中介者Mediator、具体中介者ConcreteMediator、抽象同事类Colleague和具体同事类ConcreteColleague。
 * 抽象层：Colleague关联 Mediator，具体层：ConcreteMediator关联 ConcreteColleague
 * 使用中介者模式，能实现 ConcreteColleague之间的解耦。
 * Colleague通过Mediator实现与其它Colleague的交流。因此，Colleague与Mediator存在关联关系，本例中使用聚合关系。
 * 
 * 要点：
 * 中介者本身并不产生消息，消息来源于同事类，通过中介者实现消息的收发。
 * 与观察者模式的异同点是：Subject聚合多个Observer并产生消息。
 */
abstract class Mediator {  //抽象中介者
	public abstract void dispatcherMessage(Colleague to, String message);  //发消息给谁，2个参数
}

abstract class Colleague {  //抽象同事
	protected String name;  
	protected Mediator mediator; //Colleague聚合Mediator

	public Colleague(String name) { //构造方法
		this.name = name;
	}
	
	public void setMediator(Mediator mediator) {  //setter
		this.mediator = mediator;
	}

	public void receiveMessage(Colleague from, String message) {  //普通方法：接收消息
		System.out.println(name +" receive from "+ from.name + "：" + message);
	}

	public abstract void sendMessage(String message);  //声明抽象方法
}

class ConcreteMediator extends Mediator{  //具体中介者

	//ConcreteMediator关联ConcretColleague
	private Colleague from;
	private Colleague to;

	public void setFrom(Colleague from) {
		this.from = from;
	}
	public void setTo(Colleague to) {
		this.to = to;
	}

	@Override
	public void dispatcherMessage(Colleague who, String message) {
		message = message.replaceAll("日", "*");  //屏蔽不文明语言
		if(who==from){
			to.receiveMessage(from,message);
		}else{
			from.receiveMessage(to,message);
		}
	}
}

class ConcreteColleague extends Colleague{  //具体同事
	public ConcreteColleague(String name) {  //构造方法
		super(name);
	} 
	@Override
	public void sendMessage(String message) {
		//调用中介者的转发消息方法
		mediator.dispatcherMessage(this, message);
	}
}

public class Client {  //客户端
	public static void main(String[] args) {
		//创建一个中介者
		Mediator mediator=new ConcreteMediator();

		//创建若干会员并注册到中介者
		Colleague colleague1,colleague2,colleague3;
		colleague1=new ConcreteColleague("张三"); 
		colleague1.setMediator(mediator);
		//((ConcreteMediator)mediator).setFrom(colleague1);
		colleague2=new ConcreteColleague("李四");
		colleague2.setMediator(mediator);
		//((ConcreteMediator)mediator).setFrom(colleague2);

		/*colleague3=new ConcreteColleague("王五");
		colleague3.setMediator(mediator);*/

		((ConcreteMediator) mediator).setFrom(colleague1);
		((ConcreteMediator) mediator).setTo(colleague2);
		
		//会员通过中介者转发消息
		colleague1.sendMessage("李四，你好！");
		colleague2.sendMessage("张三，你好！");
		//colleague1.sendMessage(this,"今天天气不错，有日！");
	}
}
